<template>
  <div>
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <div class="between">
            <div class="alitem">
              <el-icon @click="onClickBack">
                <ArrowLeftBold />
              </el-icon>
              <span>志愿表详情（审单）</span>
              <div class="userInfo" style="margin-left: 10px">
                <span>{{ nick }}</span>
                <span>{{ studentInfo.sex == '1' ? '女' : '男' }}</span>
                <span> {{ province }}</span>
                <span>{{ score }}分</span>
                <span>{{
                  zyInfo.section > 0 ? zyInfo.section + '位' : ''
                }}</span>
                <span>{{ sgname }}</span>
                <span>{{ batch }}</span>
              </div>
            </div>
            <div class="alitem">
              <el-tooltip effect="dark" content="个人资料" placement="top">
                <el-icon @click="userInfoChange('first')">
                  <Postcard />
                </el-icon>
              </el-tooltip>
              <!-- <el-tooltip effect="dark" content="志愿表" placement="top">
                <el-icon class="maginleft20" @click="userInfoChange('fourth3')">
                  <Tickets />
                </el-icon>
              </el-tooltip> -->
              <!-- <el-tooltip
                effect="dark"
                content="下载打印版"
                placement="top"
                v-if="zyInfo.status != 0"
              >
                <el-icon class="maginleft20" @click="downloadPrint('dy')">
                  <Printer />
                </el-icon>
              </el-tooltip>
              <el-tooltip
                effect="dark"
                content="下载合同版"
                placement="top"
                v-if="zyInfo.status != 0"
              >
                <el-icon class="maginleft20" @click="downloadPrint('ht')">
                  <Stamp />
                </el-icon>
              </el-tooltip> -->
            </div>
          </div>
        </div>
      </template>
      <el-row :gutter="20" justify="space-between">
        <el-col :span="7">
          <div class="alitem">
            <div style="margin: 0 10px; font-weight: bold">
              {{ zyInfo.title }}
            </div>
            <div style="font-size: 14px">
              数据更新时间: {{ zyInfo.lastModificationTime }}
            </div>
          </div>
        </el-col>
        <!-- <el-col :span="16" v-if="zyInfo.status != 0"> -->
        <el-col :span="16">
          <div class="alitem right" style="font-size: 15px">
            <!-- 此功能暂时只有chatgk开放 statusShow==1-->
             <!-- <div class="alitem" style="margin:0 5px" v-if="statusShow != null"> -->
             <div class="alitem" style="margin:0 5px" v-if="statusShow==1">
              <el-popconfirm
                confirm-button-text="确定"
                cancel-button-text="取消"
                :icon="InfoFilled"
                icon-color="#626AEF"
                title="确定审核通过?"
                @confirm="confirmEvent"
                @cancel="cancelEvent"
              >
                <template #reference>
                  <el-button>通过</el-button>
                </template>
              </el-popconfirm>
              <el-button type="danger" plain @click="process = true">
                驳回
              </el-button>
             </div>
            <div class="alitem" v-if="zy_type == 2">
              所有专业&nbsp;
              <el-switch v-model="allMajor" />
            </div>
            <div class="alitem" style="margin: 0 20px" v-if="zy_type == 2">
              一键展开&nbsp;
              <el-switch v-model="allUnfold" />
            </div>
            <div class="alitem" style="margin: 0 20px">
              录取概率&nbsp;
              <el-switch v-model="showChancelv" />
            </div>
            <!-- <div class="alitem" v-if="!(teacherInfo.newsc == 1)">
              同步至学生&nbsp;
              <el-switch v-model="zyInfo.isStudentSee" @change="zyInfoChange" />
            </div> -->
            <!-- sortHandleCommand -->
            <!-- <div class="curr" style="margin-right: 20px" @click="onClickUpdate">
              修改
            </div> -->
            <!-- <div
              class="curr"
              @click="onClickSave"
              :style="
                isInitialLoad ? 'color:red;border-bottom:2px solid red;' : ''
              "
            >
              保存
            </div> -->
            <!-- <el-dropdown @command="moreHandleCommand">
              <div
                class="curr"
                style="margin-left: 20px; color: #333; font-size: 15px"
                @mouseover="moreMouseover"
              >
                更多
              </div>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="save">
                    <el-button class="more-button" text>另存为</el-button>
                  </el-dropdown-item>
                  <el-dropdown-item command="download">
                    <el-button class="more-button" v-if="isDpwnLoadShow" text
                      >下载</el-button
                    >
                    <el-button class="more-button" v-else loading text
                      >下载</el-button
                    >
                  </el-dropdown-item>
                  <el-dropdown-item command="share">
                    <el-button
                      class="more-button"
                      v-if="isSharShow"
                      text
                      @mouseout="isShowQrImage = false"
                      >分享</el-button
                    >
                    <el-button class="more-button" v-else loading text
                      >分享</el-button
                    >
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown> -->
            <div
              v-show="isShowQrImage"
              class="qr-box"
              @mouseout="isShowQrImage = false"
            >
              <img style="width: 100%; height: 100%" :src="shareQrImage" />
            </div>
          </div>
        </el-col>
      </el-row>
      <div class="classifyheader margintop">
        <div class="flex sizebg">
          <div style="margin-left: 45px" class="alitem">排序</div>
          <div style="margin-left: 44px" class="alitem">录取概率</div>
          <div style="margin-left: 44px" class="alitem">院校</div>
        </div>
        <div class="flex sizeinfo">
          <div class="alitem">{{ zyInfo.today_year }}招生计划</div>
          <div style="width: 60px; margin-left: 28px" class="center">历年</div>
          <div style="width: 80px; margin-left: 28px" class="center">
            {{ zyInfo.history_year - 0 }}
          </div>
          <div style="width: 80px; margin-left: 28px" class="center">
            {{ zyInfo.history_year - 1 }}
          </div>
          <div style="width: 100px; margin-left: 28px" class="center">
            {{ zyInfo.history_year - 2 }}
          </div>
          <div style="margin-left: 80px" v-if="!allMajor">操作</div>
          <!-- <div style="margin-left: 80px" v-if="allMajor && zy_type == 2">
            填报
          </div> -->
        </div>
      </div>
      <sdVolunteerlist
        v-if="zy_type == 1"
        :status="status"
        :studentData="studentData"
        :allUnfold="allUnfold"
        :allMajor="allMajor"
        :showChancelv="showChancelv"
        :currentSort="currentSort"
        @changeSdInitialLoad="changeSdInitialLoad"
        @universityInfo="universityInfo"
        :disableUniversityInfo="disableUniversityInfo"
      />
      <jsVolunteerlist
        v-else-if="zy_type == 2"
        :status="status"
        :studentData="studentData"
        :allUnfold="allUnfold"
        :allMajor="allMajor"
        :showChancelv="showChancelv"
        :currentSort="currentSort"
        @changeInitialLoad="changeInitialLoad"
        @universityInfo="universityInfo"
        @onClickShowMajors="onClickShowMajors"
        :disableUniversityInfo="disableUniversityInfo"
      />
      <scVolunteerlist
        v-else
        :status="status"
        :studentData="studentData"
        :allUnfold="allUnfold"
        :allMajor="allMajor"
        :showChancelv="showChancelv"
        :currentSort="currentSort"
        @changeScInitialLoad="changeScInitialLoad"
        @universityInfo="universityInfo"
        :disableUniversityInfo="disableUniversityInfo"
      />
    </el-card>

    <userInfoDialog ref="userInfo" :studentData="studentData"></userInfoDialog>

    <el-dialog v-model="dialogFormVisible" title="志愿表命名" width="500">
      <el-form>
        <el-form-item label="志愿表名称" :label-width="formLabelWidth">
          <el-input
            v-model="volunteerTitle"
            autocomplete="off"
            placeholder="请输入志愿表名称"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="onClickUpdateTitle">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="process" title="表单驳回">
    <div style="padding: 5px 0;">
      备注：
    </div>
    <el-input
      v-model="textarea"
      :rows="2"
      type="textarea"
      placeholder="驳回备注"
    />
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="process = false">取消驳回</el-button>
        <el-button type="primary" @click="confirmRejection()">
          确定驳回
        </el-button>
      </span>
    </template>
  </el-dialog>
    <acceptanceRateDialog ref="acceptanceRate"></acceptanceRateDialog>
  </div>
</template>
<script setup>
import userInfoDialog from '@/views/leader/volunteer/module/userInfoDialog.vue';
import jsVolunteerlist from './module/jsVolunteerlist.vue';
import scVolunteerlist from './module/scVolunteerlist.vue';
import sdVolunteerlist from './module/sdVolunteerlist.vue';
import { useRoute, useRouter } from 'vue-router';
import bus from '@/utils/bus.js';
import { getZyInfo, zySave, gkbInfo } from '@/api/appv2/appv2.js';
import volunteersStore from '@/store/modules/volunteerInfos';
import { ElMessage } from 'element-plus';
import { InfoFilled } from '@element-plus/icons-vue'
// import QRCode from 'qrcode';
import { schoolEnrollChance,Approved } from '@/api/appv2/appv2.js';
import acceptanceRateDialog from '@/views/leader/volunteer/module/acceptanceRateDialog.vue';
const disableUniversityInfo = computed(() => equivalents.value.length == 0); // 是否能弹窗录取率
import { get } from 'lodash';
import { nextTick } from 'vue';
// 获取等效位差的公共方法
import { calculateEquivalents } from '@/utils/batchEquivalents.js';

// import useSettingsStore from '@/store/modules/settings';
// const settingsStore = useSettingsStore();
// const platformInfo = settingsStore.platformInfo;
// const teacherInfo = JSON.parse(localStorage.getItem('userDateInfo'));

// 路由信息
const router = useRouter();
// 路由信息
const route = useRoute();
// 志愿表仓库
const volunteerStore = volunteersStore();
const process = ref(false); // 驳回的对话框
const statusShow = ref(); // 是否出现通过以及驳回按钮
const nick = ref(); // 接收姓名
const province = ref(); // 接收地区
const score = ref(); // 接收分数
const userInfo = ref(null);
const sgname = ref(); // 物化生
const batchs = ref([]);
const batch = ref();
const zyInfo = ref({}); // 志愿详情信息

// 志愿表数据
const storeVolunteerInfos = computed(() => volunteerStore.volunteerInfos);
// const volunteerInfos = ref([]); // 志愿表信息
const tempVolunteerInfos = ref([]);
const index = ref(''); // 志愿表的index
const zy_type = ref(''); // 志愿表的index
const zyId = ref(''); // xiangqing
const studentData = ref({}); // 学生数据
const studentInfo = ref({}); // 学生信息
const allUnfold = ref(false); // 是否一键展开
const allMajor = ref(false); // 是否显示所有专业
const showChancelv = ref(true); // 是否显示录取率
const textarea = ref(); // 驳回时的备注
const dialogFormVisible = ref(false); // 是否显示修改志愿表名称弹窗
const volunteerTitle = ref(''); // 志愿表标题
const sgid = ref();
const id = ref()
const volunteerInfoslist = ref(); // 院校地collegeCode的id集合
const isShowQrImage = ref(false); // 是否显示分享二维码
// const shareUrl = ref(null); // 分享地址
const shareQrImage = ref(null); // 分享二维码图片
const currentSort = ref('0'); // 当前排序 chance-录取率 rank-院校排名 position-位次
const isInitialLoad = ref(false);
// const isDpwnLoadShow = ref(true);
// const isSharShow = ref(true);

const { id: teacherId, groupId } = JSON.parse(
  localStorage.getItem('userDateInfo')
);
const confirmEvent = () => { // 点击通过中的确定
  Approved({
    id:id.value,
    status:3,
    remark: '审核通过'
  }).then((res)=>{
    console.log(res);
    statusShow.value = null
    ElMessage({
      message: '操作成功',
      type: 'success',
    })
  })
}
const cancelEvent = () => { // 点击通过中的取消
  // console.log('cancel!')
  ElMessage({
    message: '取消审核',
    type: 'warning',
  })
}
const confirmRejection = () => { // 确认驳回按钮
  Approved({
    id:id.value,
    status:2,
    remark: textarea.value
  }).then((res)=>{
    console.log(res);
    textarea.value = ''
    statusShow.value = null
    ElMessage({
      message: '操作成功',
      type: 'success',
    })
  })
  process.value = false
}
const onClickShowMajors = (batch, collegeCode, id, index) => {
  // console.log('batch, collegeCode, id, index:', batch, collegeCode, id, index);
  // 如果传入单个code，就是点击每一行，如果传入的是数组，就是点击头部按钮
  const params = {
    studentId: studentData.value.studentId,
    batch: batch.value,
    // scode: formatCollegeCode(collegeCode),
    scode: volunteerInfoslist.value,
    sgid: sgid.value,
    score: score.value,
    // pageSize: 100,
    course: localStorage.getItem('courseNew'),
  };
  storeVolunteerInfos.value = volunteerStore.volunteerInfos;
  schoolEnrollChance(params)
    .then((res) => {
      localStorage.setItem('courseNew', res.data.scoreConfigData.course || '');
      batchEqus.value = res.data.batchEqus;
      if (!!index) {
        storeVolunteerInfos.value[index].allMajorsList = res.data.list.filter(
          (item) => item.id == id
        )[0]?.majorsInfo;
      } else {
        // console.log( storeVolunteerInfos.value,'storeVolunteerInfos.volunteerInfos' );
        // console.log('res.data.list', res.data.list)

        storeVolunteerInfos.value.forEach((itemA) => {
          const matchingItemB = res.data.list.find(
            (itemB) => itemB.id === itemA.id
          );
          // console.log(matchingItemB, 'matchingItemB');

          if (matchingItemB) {
            storeVolunteerInfos.value;
            itemA.allMajorsList = calculateEquivalents(
              matchingItemB.majorsInfo,
              batchEqus.value
            );
          }
        });
      }
      // 获取等效位差的公共方法
      storeVolunteerInfos.value = calculateEquivalents(
        storeVolunteerInfos.value,
        batchEqus.value
      );
      nextTick(() => {
        volunteerStore.setVolunteerInfos(storeVolunteerInfos.value);
      });
    })
    .catch((err) => {
      console.log('err:', err);
    });
};

// 当前志愿表状态 0不可编辑
const status = ref(0);
const changeInitialLoad = (isInitial) => {
  isInitialLoad.value = isInitial;
};
const changeSdInitialLoad = (sdIsInitial) => {
  isInitialLoad.value = sdIsInitial;
};
const changeScInitialLoad = (scIsInitial) => {
  isInitialLoad.value = scIsInitial;init
};
bus.emit('handlePathTextChange', '编辑志愿表');

onBeforeRouteLeave((to, from, next) => {
  bus.emit('handlePathTextChange', '');
  next();
});

init();

function init() {
  let data = JSON.parse(decodeURIComponent(atob(route.query.data)));
  console.log(data,"1112233");
  id.value = data.id
  // statusShow.value = data.status
  zyId.value = data.zyId;
  studentData.value.studentId = data.studentId;
  studentData.value.pid = data.pid;
  status.value = data.status;
  nick.value = data.nick;
  province.value = data.province;
  sgname.value = data.sgname;
  zy_type.value = data.zy_type;
  score.value = data.score;
  sgid.value = data.sgid;
  volunteerStore.setVolunteerInfos(null);
  getVolunteerInfo();
  gkbInfo({
    pid: studentData.value.pid,
    studentId: studentData.value.studentId,
  }).then(() => {
  });
}

//录取率弹窗
const acceptanceRate = ref(null);
const universityInfo = (data, isMajor) => {
  acceptanceRate.value.open(data, isMajor, equivalents, batchs);
};

function onClickBack() {
  // router.back(2);
  router.replace({
    path: '/leader/Examine',
  });
}

function userInfoChange(val) {
  userInfo.value.openChange(val);
}
const equivalents = ref({}); // 线差所需要的年份集合
const batchEqus = ref({}); // 线差所需要的批次新集合
// 获取志愿表信息
function getVolunteerInfo() {
  getZyInfo({
    id: zyId.value,
    studentId: studentData.value.studentId,
  }).then((res) => {
    // console.log(res, '志愿表信息');
    batch.value = batch.value = res.data.batch || '/';
    equivalents.value = res.data.equivalents;
    batchEqus.value = res.data.batchEqus;
    localStorage.setItem('equivalents', JSON.stringify(res.data.equivalents));
    localStorage.setItem('course', res.data.course || '');
    statusShow.value = res.data.is_subStatus
    status.value = res.data.is_subStatus || status.value;
    batchs.value = res.data.batchs;
    zyInfo.value = res.data;

    volunteerInfoslist.value = res.data.volunteerInfos
      .map((item) => item.collegeCode)
      .join(',');
    zyInfo.value.isStudentSee = !!zyInfo.value.isStudentSee;
    const volunteer = zyInfo.value.volunteerInfos;
    var volunteerInfos = [];

    // 判断是否为array类型，否则为历史老数据object类型，兼容为array类型
    if (!Array.isArray(volunteer)) {
      for (let key in volunteer) {
        let info = volunteer[key].collegeData;
        info.majorsInfo = volunteer[key].majorsInfo;
        info.vkey = key;

        volunteerInfos.push(info);
      }
    } else {
      volunteerInfos = volunteer;
    }

    volunteerInfos.value = volunteerInfos;
    // 获取等效位差的公共方法
    volunteerInfos.value = calculateEquivalents(
      volunteerInfos.value,
      batchEqus.value
    );
    tempVolunteerInfos.value = volunteerInfos;
    volunteerTitle.value = zyInfo.value.title;
    volunteerStore.setVolunteerInfos(volunteerInfos.value);
  });
}

// 快速排序
// function sortHandleCommand(type) {
//   // 判断 zy_type 的值
//   if (zy_type.value === 3) {
//     // 如果需要操作嵌套的 value 数据
//     volunteerInfos.value = flattenVolunteerInfos(volunteerStore.volunteerInfos);
//   } else {
//     volunteerInfos.value = [...volunteerStore.volunteerInfos]; // 复制数据
//   }

//   // 调用排序逻辑
//   volunteerInfosSort(type);

//   // 增加排序标识
//   currentSort.value += 1;
// }
// 展平数据函数
// function flattenVolunteerInfos(data) {
//   // 处理数据结构，解开 value 中的嵌套数据
//   const flatData = data.slice(0, -1); // 取出前面的普通数据
//   const nestedData = data[data.length - 1]?.value || []; // 获取最后一项的 value 数据
//   return [...flatData, ...nestedData]; // 合并普通数据和 value 数据
// }
// 志愿表排序
// function volunteerInfosSort(sortKey) {
//   // 检查 sortKey 是否存在
//   if (sortKey === 'minRank') {
//     // 处理 minRank 排序逻辑
//     volunteerInfos.value = volunteerInfos.value
//       .slice() // 创建副本
//       .sort((a, b) => {
//         // 获取 a 和 b 的 enterRank
//         const minRankA = a.enterRank;
//         const minRankB = b.enterRank;

//         // 如果 a 和 b 都没有 minRank，保持原顺序
//         if (minRankA === undefined && minRankB === undefined) return 0;

//         // 如果 a 没有 minRank，将 a 排在后面
//         if (minRankA === undefined) return 1;

//         // 如果 b 没有 minRank，将 b 排在后面
//         if (minRankB === undefined) return -1;

//         // 如果 a 和 b 都有 minRank，按 minRank 升序排序
//         return minRankB - minRankA;
//       });

//     // 更新原始数据
//     volunteerStore.setVolunteerInfos(volunteerInfos.value);
//   } else {
//     // 其他 sortKey 的排序逻辑
//     if (!volunteerInfos.value[0]?.hasOwnProperty(sortKey)) return;

//     volunteerInfos.value = volunteerInfos.value
//       .slice() // 创建副本
//       .sort((a, b) => {
//         const valueA = a[sortKey];
//         const valueB = b[sortKey];

//         // 处理数字类型排序
//         if (typeof valueA === 'number' && typeof valueB === 'number') {
//           return valueA - valueB;
//         }

//         // 处理字符串类型排序
//         if (typeof valueA === 'string' && typeof valueB === 'string') {
//           return valueA.localeCompare(valueB);
//         }

//         return 0; // 其他类型保持原顺序
//       });

//     // 更新原始数据
//     volunteerStore.setVolunteerInfos(volunteerInfos.value);
//   }
// }
// 修改志愿表标题
function onClickUpdateTitle() {
  dialogFormVisible.value = false;
  zyInfo.value.title = volunteerTitle.value;

  let data = {};
  data['title'] = volunteerTitle.value;

  updateZyInfo(data);
}

// 更新志愿表信息
function updateZyInfo(data) {
  data['index'] = index.value;
  data['studentId'] = studentData.value.studentId;
  data['teacherId'] = teacherId;
  data['groupId'] = groupId;
  zySave(data).then(() => {
    tempVolunteerInfos.value = JSON.parse(get(data, 'volunteerInfos', '{}'));
    isInitialLoad.value = false;
    // 修改成功
    ElMessage({
      message: '更新成功',
      type: 'success',
    });
  });
}
</script>
<style lang="scss" scoped>
:deep(.el-dialog__footer) {
  padding: 20px;
}
.more-button {
  width: 100px;
}

.box-card {
  margin: 20px;
  width: auto;
  height: calc(100vh - 120px);
  overflow-y: auto;

  .tabs {
    color: #000000;
    font-weight: 600;
    cursor: pointer;
  }

  .active {
    color: #004cf7;
    font-weight: 600;
    cursor: pointer;
  }

  .card-header {
    font-size: 20px;
    font-weight: 600;
    color: #1d2129;
    padding: 10px;

    .userInfo {
      margin-left: 30px;
      font-size: 16px;
      font-weight: 400;
      color: #1d2129;
      line-height: 16px;

      span {
        margin-left: 8px;
      }
    }

    .headerSize {
      color: #4e5969;
      font-size: 14px;
      margin-left: 12px;
      font-weight: 400;
      height: 20px;
      line-height: 21px;
    }
  }
}

.classifyheader {
  background: #fafafa;
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  color: #86909c;
  letter-spacing: 0;
  line-height: 28px;
  padding-right: 80px;
}

.qr-box {
  position: absolute;
  top: 180px;
  right: 0;
  width: 120px;
  height: 120px;
  border: 1px #efefef solid;
  padding: 5px;
  background-color: white;
  z-index: 999;
  box-shadow: 1px 1px 4px 1px #efefef;
  border-radius: 5px;
}
</style>
